package net.stancristian.restnews;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Scanner;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.auth.AuthenticationException;
import org.apache.http.auth.MalformedChallengeException;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.auth.DigestScheme;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHttpRequest;
import org.json.JSONArray;
import org.json.JSONObject;

//Rest News Client
public class RestNewsClient {
	public static String userName;
	public static String password;
	public static DigestScheme md5Auth = new DigestScheme();
	public static Header challenge = null;

	public static HttpResponse getRequestWebService(String urlString) {

		HttpResponse response = null;
		try {

			HttpGet request = new HttpGet(urlString);
			DefaultHttpClient client = new DefaultHttpClient();
			SetAuthorizationHeader(request, client, urlString, "GET");

			response = client.execute(request);
			return response;

		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (HttpException e) {
			e.printStackTrace();
		}

		return null;
	}

	/*
	 * Get a JSON from a response
	 */
	public static JSONObject GetJsonObjectFromResponse(HttpResponse response) {
		JSONObject jsonobject = null;
		try {
			HttpEntity entity = response.getEntity();
			InputStream contentStream = entity.getContent();
			String responseBody = getResponseText(contentStream);
			jsonobject = new JSONObject(responseBody);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsonobject;
	}
	
	/*
	 * Get a JSON from a response
	 */
	public static JSONArray GetJsonArrayFromResponse(HttpResponse response) {
		JSONArray jsonArray = null;
		try {
			HttpEntity entity = response.getEntity();
			InputStream contentStream = entity.getContent();
			String responseBody = getResponseText(contentStream);
			jsonArray = new JSONArray(responseBody);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsonArray;
	}

	private static String getResponseText(InputStream inStream) {
		// very nice trick from
		// http://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner_1.html
		return new Scanner(inStream).useDelimiter("\\A").next();
	}

	/*
	 * Sets the Authorization Header
	 */
	private static void SetAuthorizationHeader(HttpRequest request,
			DefaultHttpClient client, String url, String methodName)
			throws MalformedChallengeException, AuthenticationException,
			ClientProtocolException, IOException {

		if (challenge == null) {
			HttpResponse response = null;

			if (methodName == "GET") {
				response = client.execute(new HttpGet(url));
			} else if (methodName == "POST") {
				response = client.execute(new HttpPost(url));
			} else if (methodName == "PUT") {
				response = client.execute(new HttpPut(url));
			} else if (methodName == "DELETE") {
				response = client.execute(new HttpDelete(url));
			}

			StatusLine status = response.getStatusLine();
			if (status.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
				challenge = response.getHeaders("WWW-Authenticate")[0];
				
			}
		}
		md5Auth.processChallenge(challenge);
		Header solution = md5Auth.authenticate(new UsernamePasswordCredentials(
				userName, password), new BasicHttpRequest(methodName, new URL(
				url).getPath()));

		request.setHeader(solution);

	}
}
